const { Op } = require("sequelize");
const db = require("../models/index")
const dbF = {
  user:"model_User_F",
  article:"model_article",
  comment:"model_comment",
  category:"model_blog_category",
  carousel:"model_carousel",
  follows:"model_user_follows"
}
function ifInclude(include){
  const temp = include
  if(include){
    include = [{
      model:db[dbF[include[0].model]] ,
      attributes: include[0].attributes,
    }]
    console.log(include)
    return include
  }else{
    return []
  }
 
}
function Pair(data) {
  if (isJSON(data)) data = JSON.parse(data);
  let {
    key = "",
    value = [""],
    OpLike = "",
    Or = "",
    Not = "",
    And = "",
  } = data;
  if (value[0] == "") Or = false;
  key = key || [];
  let temp = {};
  for (let index = 0; index < key.length; index++) {
    if (value[index] != undefined && value[index] != "") {
      if (OpLike == "true") {
        temp[key[index]] = { [Op.like]: `%${value[index]}%` };
      } else {
        if (value[index][0] == "time") {
          const head = DataUTC(`${value[index][1]} 00:00:00+0800`);
          const tail = DataUTC(`${value[index][2]} 23:59:59+0800`);
          temp[key[index]] = {
            [Op.gt]: head,
            [Op.lt]: tail,
          };
        } else {
          temp[key[index]] = value[index];
        }
      }
      if (Or == "true") {
        const orTemp = temp;
        temp = {};
        temp[Op.or] = dataOr(key, orTemp);
      }
      if (value[index] == "null") {
        temp[key[index]] = null;
      }
    }
  }
  if (Not != "") {
    temp[`${Not[0]}`] = {
      [Op.not]: Not[1],
    };
  }
  if (And != "") {
    temp[Op.and] = And;
  }
  return temp;
}
// 进行 Or 组装
function dataOr(key, value) {
  const OrTemp = key.map((data) => {
    const obj = {};
    obj[data] = Object.values(value)[0];
    return obj;
  });
  return OrTemp;
}
// 对时间对象进行时区矫正
function DataUTC(time) {
  const dateString = `${time}`;
  const parts = dateString.split(/([+-]\d{2})(\d{2})$/);
  const date = new Date(parts[0]);
  date.setUTCMinutes(
    date.getUTCMinutes() + parseInt(parts[1]) * 60 + parseInt(parts[2])
  );
  return date;
}
// 判断对象是否为 JSON
function isJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}
// 禁止返回的列
const outOptions =["password","wxopen_id"]
function outOption(value){
  if (Array.isArray(value)) {
    for (let index = 0; index < value.length; index++) {
      for (let temp = 0; temp < outOption.length; temp++) {
        let indexOF = value.indexOf(outOption[temp]);
        if (indexOF !== -1) {
          value.splice(indexOF, 1); 
        } else {
        }
      }
    }
  }else{
    return value
  }
  return value
}
var counts = 0
exports.create = (app) => {
  // 查找数据
  const Search = async (req, res) => {
    try {
      console.log("进入Search--" + ++counts);
      console.log(req.query)
      let {
        data,
        include = null,
        columns = { exclude: outOptions },
        limit = null,
        offset = null,
        order = null,
      } = req.query;
      // include = ifInclude(include)
      columns = outOption(columns)
      const searchData = Pair(data);
      const count = await app.count({ where: searchData });
      const result = await app.findAll({
        attributes: columns,
        where: searchData,
        // 实现联合查询，减少服务器  axios 请求
        // include: include || null,
        limit: limit ? Number(limit) : null,
        offset: offset ? (Number(offset) - 1) * limit : null,
        order: order,
      });
      res.send({
        data: result,
        count: count,
      });
    } catch (err) {
      console.log(err);
      res.status(400).send({
        message: false,
      });
    }
  };

  // 增加数据
  const add = async (req, res) => {
    try {
      console.log("进入Add");
      console.log(req.body)
      const data = Pair(req.body.data);
      await app.create(data);
      res.send({ message: true });
    } catch (error) {
      console.log(error);
      res.status(400).send({ message: false });
    }
  };

  // 删除数据
  const destroy = async (req, res) => {
    try {
      console.log("进入Destroy");
      const data = Pair(req.body.data);
      if (Object.keys(data).length === 0) {
        res.send({
          message: false,
        });
        return;
      }
      await app.destroy({ where: data });
      res.send({
        message: true,
      });
    } catch (error) {
      console.log(error);
      res.status(400).send({
        message: false,
      });
    }
  };

  // 更新数据
  const update = async (req, res) => {
    try {
      console.log("update");
      const data = Pair(req.body.data);
      const where = Pair(req.body.where);
      await app.update(data, { where: where });
      res.send({
        message: true,
      });
    } catch (error) {
      console.log(error);
      res.status(400).send({
        message: false,
      });
    }
  };

  return {
    add,
    destroy,
    update,
    Search,
  };
};
